package com.buddy.learn.network.nio.channel;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author WongZP
 * @date 2022/4/18
 */
public class NIOServer {

    public static void main(String[] args) {
        try {
            // 打开一个服务端通道
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            // 绑定端口
            serverSocketChannel.bind(new InetSocketAddress(8088));
            // 通道默认是阻塞的，需要设置为非阻塞
            serverSocketChannel.configureBlocking(false);
            System.out.println("start server ...");
            while (true){
                // 检查是否有客户端连接，返回客户端连接的通道
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (Objects.isNull(socketChannel)){
                    // 通道为null 如果没有客户端连接
                    System.out.println("none client connection...");
                    Thread.sleep(2000);
                    continue;
                }
                // 获取到客户端连接，把数据放到 bytebuffer中
                ByteBuffer allocate = ByteBuffer.allocate(1024);
                // 0 没有读到数据，-1读到末尾，正数读到的有效字节数
                int read = socketChannel.read(allocate);
                String string = new String(allocate.array(), 0, read, StandardCharsets.UTF_8);
                System.out.println(string);
                // 给客户端返回数据
                socketChannel.write(ByteBuffer.wrap("hello client".getBytes(StandardCharsets.UTF_8)));
                // 释放资源
                socketChannel.close();
            }
        } catch (IOException | InterruptedException ioException) {
            ioException.printStackTrace();
        }
    }
}
